class Sales::SessionsController < ApplicationController
  layout "sessions"
  before_action :set_customer, only:[:create]
  before_action :set_store_id
  def new
  end

  def create
    status = AuthenticateStafferService.call(@customer, params[:password])
    if status.success?
      session[:customer_id] = @customer.id
      # set_current_cart
      redirect_to session[:redirect_to] || sales_store_products_path(store_id: set_normal_store_id)
    else
      redirect_to new_sales_session_path(store_id: @store_id), notice: status.message
    end
  end

  def destroy
    session[:customer_id] = nil
    session[:cart_id] = nil
    redirect_to new_sales_session_path(store_id: @store_id)
  end


  private
  def set_customer
    @customer = StoreCustomer.find_by(login_name: params[:login_name])
  end

  def set_store_id
    @store_id ||= params[:store_id]
  end

  def set_normal_store_id
    @norrmal_store_id ||= decode(@store_id)
  end

  def set_current_cart
    @cart = Cart.find_or_create_by(store_id: set_normal_store_id, store_customer_id: @customer.id)
    session[:cart_id] = @cart.id
  end

end
